import React from "react";
import { Button, Icon, Upload } from "antd";
import DocSelectModal from "../DocSelectModal/";
import { cloneDeep } from "lodash";

class FileUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showDocLibModal: false
    };
  }

  handleChange = info => {
    const { limit } = this.props;
    let fileList = info.fileList;

    // 1. Limit the number of uploaded files
    //    Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-limit || -1);

    // 2. read from response and show file link
    fileList = fileList.map(file => {

      if (file.response && !file._id) { // if _id exists, the file is from doc lib
        // Component will show file.url as link
        file.url = file.response.url;
      }
      // const { response, url, name, uid } = file;
      // return { response, url, name, uid };
      return file;
    });

    // 3. filter successfully uploaded files according to response from server
    fileList = fileList.filter(file => {
      if (file.response) {
        return file.response.status === "success";
      }
      return true;
    });
    this.props.onFileUpload(fileList);
  };

  addFromLib = (file) => {
    const { fileList, onFileUpload } = this.props;
    fileList.push(file);
    onFileUpload(fileList);
  }

  openDocLibModal = () => {
    const {showDocLibModal} = this.state;
    this.setState({showDocLibModal: !showDocLibModal});
  }

  render() {
    const { action = "/api/upload", fileList = [] } = this.props;
    const { showDocLibModal } = this.state;
    const configs = {
      action,
      onChange: this.handleChange,
      multiple: true,
    };
    const cFL = fileList.map(fl => {
      if (fl._id) {
        fl.uid = fl._id;
        fl.name = fl.docName;
        fl.response = {
          status: "success"
        };
      }
      return cFL;
    });
    return (
      <div>
        <Button onClick={this.openDocLibModal} style={{marginRight: 8}}>
          {showDocLibModal?'关闭文档库':<span><Icon type="file-add" />从文档库添加</span>}
        </Button>
        {showDocLibModal && <DocSelectModal addFromLib={this.addFromLib} fileList={cloneDeep(fileList)}  />}
        <Upload {...configs} fileList={fileList}>
          <Button>
            <Icon type="upload" />从本地上传
          </Button>
        </Upload>
      </div>
    );
  }
}

export default FileUpload;
